package com.ljx.recruitment.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.ljx.recruitment.common.exception.ApiException;
import com.ljx.recruitment.user.domain.vo.req.EmailSendReq;
import com.ljx.recruitment.user.domain.vo.resp.EmailSendResp;
import com.ljx.recruitment.user.enums.EmailTypeEnum;
import com.ljx.recruitment.user.service.EmailService;
import com.ljx.recruitment.user.service.EmailSendService;
import com.ljx.recruitment.user.service.impl.email.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Author: LiJunXi
 * @Description:
 * @Date: 2024-10-30  22:15
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public EmailSendResp doSendEmail(EmailSendReq req) {
        checkParams(req);
        EmailSendService emailSendService = getSendEmailService(req.getType());
        fillEmailSendReqParams(req);
        return emailSendService.sendEmail(mailSender, req);
    }

    private void checkParams(EmailSendReq req) {
        if (StrUtil.isEmpty(req.getTo()) || Objects.isNull(req.getType())){
            throw new ApiException("必要参数不能为空");
        }
    }

    private void fillEmailSendReqParams(EmailSendReq req) {
        Map<String, String> map = req.getDetailsMap();
        if (Objects.isNull(map)){
            map = new HashMap<>();
        }
        req.setFrom(fromEmail);
        req.setDetailsMap(map);
    }

    private EmailSendService getSendEmailService(Integer type) {
        if (type.equals(EmailTypeEnum.REGISTER.getKey())){
            return new RegisterEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.RESUME_SCREENING.getKey())){
            return new ResumeScreeningEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.WRITTEN_EXAMINE.getKey())){
            return new WrittenExaminationEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.MAJOR_INTERVIEW.getKey())){
            return new MajorInterviewEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.HR_INTERVIEW.getKey())){
            return new HrInterviewEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.OFFER.getKey())){
            return new OfferEmailSendServiceImpl();
        } else if(type.equals(EmailTypeEnum.SALVAGE.getKey())){
            return new SalvageEmailSendServiceImpl();
        } else {
            throw new ApiException("未知邮件类型");
        }
    }
}
